// API基础配置
const API_BASE_URL = 'http://localhost:3001/api';

// 通用请求函数
async function request(endpoint, options = {}) {
  try {
    // 设置超时
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000); // 30秒超时
    
    // 添加时间戳参数以避免缓存
    const url = `${API_BASE_URL}${endpoint}${endpoint.includes('?') ? '&' : '?'}_t=${Date.now()}`;
    
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0',
        ...options.headers,
      },
      ...options,
      signal: controller.signal,
      // 添加缓存控制
      cache: 'no-cache'
    });
    
    clearTimeout(timeoutId);
    
    // 检查响应类型
    const contentType = response.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
      const text = await response.text();
      throw new Error(`服务器返回非JSON响应: ${text.substring(0, 100)}...`);
    }
    
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || '请求失败');
    }

    return data;
  } catch (error) {
    if (error.name === 'AbortError') {
      throw new Error('请求超时，请稍后重试');
    }
    console.error('API请求错误:', error);
    throw error;
  }
}

// 货位数据API

// 获取所有货位数据
export async function getAllSlots() {
  const response = await request('/slots');
  return response.data;
}

// 获取单个货位详情
export async function getSlotById(slotId) {
  const response = await request(`/slots/${slotId}`);
  return response.data;
}

// 获取无货货位（不考虑任务状态）
export async function getEmptySlots() {
  const response = await request('/slots/empty');
  return response.data;
}

// 获取可用货位（无货且无未下发任务）
export async function getAvailableSlots() {
  const response = await request('/slots/available');
  return response.data;
}

// 获取未下发任务
export async function getUnissuedTasks() {
  try {
    console.log('🔍 请求未下发任务数据');
    // 为未下发任务请求添加额外的缓存控制
    const response = await request('/tasks/unissued', {
      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
      }
    });
    console.log('✅ 未下发任务数据获取成功', response);
    return response.data;
  } catch (error) {
    console.error('❌ 获取未下发任务失败:', error);
    throw error;
  }
}

// 初始化货位数据（批量插入）
export async function initializeSlots(warehouseData) {
  const response = await request('/slots/init', {
    method: 'POST',
    body: JSON.stringify(warehouseData),
  });
  return response.data;
}

// 更新货位状态
export async function updateSlot(slotId, hasGoods, goodsInfo = null) {
  const response = await request(`/slots/${slotId}`, {
    method: 'PUT',
    body: JSON.stringify({ hasGoods, goodsInfo }),
  });
  return response.data;
}

// 获取统计信息
export async function getStatistics() {
  const response = await request('/statistics');
  return response.data;
}

// 健康检查
export async function healthCheck() {
  const response = await request('/health');
  return response.data;
}

// 保存配置到文件
export async function saveConfig(config) {
  const response = await request('/config', {
    method: 'POST',
    body: JSON.stringify(config),
  });
  return response.data;
}

// 获取配置文件
export async function getConfig() {
  const response = await request('/config');
  return response.data;
}

// 重新初始化数据
export async function reinitializeData() {
  const response = await request('/reinitialize', {
    method: 'POST'
  });
  return response.data;
}

// 导出通用请求函数
export { request };